package cn.tworice.ocr.tess4j.service;

import cn.tworice.common.util.file.FileConvertUtil;
import cn.tworice.ocr.constand.FileType;
import cn.tworice.ocr.exception.OCRException;
import cn.tworice.ocr.tess4j.OCRClient;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;

@Service
public class OCRService {

    private OCRClient ocrClient;


    public String ocr(MultipartFile img) throws IOException {
        String fileType = Objects.requireNonNull(img.getOriginalFilename()).substring(img.getOriginalFilename().lastIndexOf(".") + 1);
        if (FileType.PNG.equals(fileType) || FileType.JPG.equals(fileType)) {
            BufferedImage convert = FileConvertUtil.convert(img);
            if (ocrClient == null) {
                ocrClient = new OCRClient();
            }
            try {
                return ocrClient.ocr(convert);
            } catch (TesseractException e) {
                e.printStackTrace();
                return null;
            }
        }else {
            throw new OCRException("请上传图片");
        }
    }
}
